package com.mall.service.impl;

import com.mall.common.BusinessException;
import com.mall.dto.CartOperateDTO;
import com.mall.entity.Cart;
import com.mall.entity.Product;
import com.mall.mapper.CartMapper;
import com.mall.mapper.ProductMapper;
import com.mall.service.CartService;
import com.mall.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public void addToCart(Long userId, CartOperateDTO.AddToCartDTO addToCartDTO) {
        Product product = productMapper.selectById(addToCartDTO.getProductId());
        if (product == null || product.getStatus() != 1) {
            throw new BusinessException("商品不存在或已下架");
        }
        if (product.getStock() < addToCartDTO.getQuantity()) {
            throw new BusinessException("商品库存不足");
        }

        Cart existingCart = cartMapper.selectByUserIdAndProductId(userId, addToCartDTO.getProductId());
        if (existingCart != null) {
            int newQuantity = existingCart.getQuantity() + addToCartDTO.getQuantity();
            if (product.getStock() < newQuantity) {
                throw new BusinessException("商品库存不足");
            }
            existingCart.setQuantity(newQuantity);
            existingCart.setUpdateTime(LocalDateTime.now()); // 修复4
            cartMapper.updateById(existingCart);
        } else {
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(addToCartDTO.getProductId());
            cart.setQuantity(addToCartDTO.getQuantity());
            cart.setChecked(true);
            cart.setCreateTime(LocalDateTime.now());  // 修复3
            cart.setUpdateTime(LocalDateTime.now());  // 修复3
            cartMapper.insert(cart);
        }
    }

    @Override
    public CartVO.CartSummaryVO getCartList(Long userId) {
        List<Cart> cartItems = cartMapper.selectByUserIdWithProduct(userId);
        return buildCartSummaryVO(cartItems);
    }

    @Override
    @Transactional
    public void updateCartQuantity(Long userId, CartOperateDTO.UpdateCartDTO updateCartDTO) {
        Cart cart = cartMapper.selectById(updateCartDTO.getCartId());
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new BusinessException("购物车项不存在");
        }

        Product product = productMapper.selectById(cart.getProductId());
        if (product == null || product.getStock() < updateCartDTO.getQuantity()) {
            throw new BusinessException("商品库存不足");
        }

        cart.setQuantity(updateCartDTO.getQuantity());
        cart.setUpdateTime(LocalDateTime.now()); // 修复4
        cartMapper.updateById(cart);
    }

    @Override
    @Transactional
    public void updateCartChecked(Long userId, CartOperateDTO.UpdateCartDTO updateCartDTO) {
        Cart cart = cartMapper.selectById(updateCartDTO.getCartId());
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new BusinessException("购物车项不存在");
        }

        cart.setChecked(updateCartDTO.getChecked() != null && updateCartDTO.getChecked());
        cart.setUpdateTime(LocalDateTime.now()); // 修复4
        cartMapper.updateById(cart);
    }

    @Override
    @Transactional
    public void batchSelectCart(Long userId, CartOperateDTO.BatchSelectDTO batchSelectDTO) {
        cartMapper.updateCheckedByUserId(userId, batchSelectDTO.getChecked() ? 1 : 0);
    }

    @Override
    @Transactional
    public void removeFromCart(Long userId, Long cartId) {
        Cart cart = cartMapper.selectById(cartId);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new BusinessException("购物车项不存在");
        }
        cartMapper.deleteById(cartId);
    }

    @Override
    @Transactional
    public void batchRemoveFromCart(Long userId, Long[] cartIds) {
        if (cartIds != null && cartIds.length > 0) {
            List<Long> idList = new ArrayList<>();
            for (Long cartId : cartIds) {
                Cart cart = cartMapper.selectById(cartId);
                if (cart != null && cart.getUserId().equals(userId)) {
                    idList.add(cartId);
                }
            }
            if (!idList.isEmpty()) {
                cartMapper.deleteBatchByIds(idList);
            }
        }
    }

    @Override
    @Transactional
    public void clearCart(Long userId) {
        cartMapper.deleteByUserId(userId);
    }

    @Override
    @Transactional
    public void clearCheckedCart(Long userId) {
        cartMapper.deleteCheckedByUserId(userId);
    }

    @Override
    public Long getCartCount(Long userId) {
        return cartMapper.countByUserId(userId);
    }

    @Override
    public CartVO.CartSummaryVO getCheckedCartItems(Long userId) {
        List<Cart> cartItems = cartMapper.selectCheckedByUserIdWithProduct(userId);
        return buildCartSummaryVO(cartItems);
    }

    @Override
    public boolean validateCartItems(Long userId, Long[] cartIds) {
        if (cartIds == null || cartIds.length == 0) {
            return false;
        }

        for (Long cartId : cartIds) {
            Cart cart = cartMapper.selectById(cartId);
            if (cart == null || !cart.getUserId().equals(userId)) {
                return false;
            }

            Product product = productMapper.selectById(cart.getProductId());
            if (product == null || product.getStatus() != 1 || product.getStock() < cart.getQuantity()) {
                return false;
            }
        }

        return true;
    }

    /**
     * 构建购物车汇总VO
     */
    private CartVO.CartSummaryVO buildCartSummaryVO(List<Cart> cartItems) {
        List<CartVO> itemVOs = new ArrayList<>();
        for (Cart cart : cartItems) {
            Product product = productMapper.selectById(cart.getProductId());
            if (product != null && product.getStatus() == 1) {
                CartVO vo = new CartVO();
                vo.setId(cart.getId());
                vo.setUserId(cart.getUserId());
                vo.setProductId(cart.getProductId());
                vo.setQuantity(cart.getQuantity());
                vo.setChecked(Boolean.TRUE.equals(cart.getCheckstatus())); // 防止 null
                vo.setCreateTime(cart.getCreateTime());
                vo.setUpdateTime(cart.getUpdateTime());
                vo.setProductName(product.getName());
                vo.setProductImage(product.getMainImage());                // 注意字段名
                vo.setProductPrice(product.getPrice());
                vo.setStatus(product.getStatus());
                vo.setStock(product.getStock());

                // 小计金额
                BigDecimal total = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
                vo.setTotalAmount(total);

                itemVOs.add(vo);
            }
        }

        CartVO.CartSummaryVO summaryVO = new CartVO.CartSummaryVO();
        summaryVO.setCartItems(itemVOs);
        summaryVO.calculateSummary();
        return summaryVO;
    }

    // 管理端：获取全部购物车项
    @Override
    public java.util.List<Cart> listAll() {
        return cartMapper.selectAll();
    }

    // 管理端：根据ID获取购物车项
    @Override
    public Cart getById(Long id) {
        return cartMapper.selectById(id);
    }

    // 管理端：新增购物车项
    @Override
    public void add(Cart cart) {
        cartMapper.insert(cart);
    }

    // 管理端：更新购物车项
    @Override
    public void update(Cart cart) {
        cartMapper.updateById(cart);
    }

    // 管理端：删除购物车项
    @Override
    public void delete(Long id) {
        cartMapper.deleteById(id);
    }
}